package resources;

import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.server.resources.CoapExchange;

/**
 * describe:
 *
 * @author helloworldyu
 * @data 2017/12/6
 */
public class StatusResource extends BaseResource{
	public static final String URL = "devices/${deviceId}/status";

	public StatusResource() {
		super(URL);
		getAttributes().setTitle("Sensor Status operation");
	}

	@Override
	public void handlePOST(CoapExchange exchange) {
		byte[] requestPayload = exchange.getRequestPayload();
		System.out.println( "deviceId:" + getDeviceId(exchange) + ",数据:"+new String(requestPayload));

		String token = getToken(exchange);
		if( null != token ){
			System.out.println("token:"+token);
			exchange.respond(CoAP.ResponseCode.CREATED,"post status ok");
		}else {
			exchange.respond(CoAP.ResponseCode.BAD_OPTION,"can not find token");
		}

	}

	@Override
	public void handleDELETE(CoapExchange exchange) {
		byte[] requestPayload = exchange.getRequestPayload();
		System.out.println( "deviceId:" + getDeviceId(exchange));
		exchange.respond(CoAP.ResponseCode.DELETED,"delete status ok");
	}

	@Override
	public void handlePUT(CoapExchange exchange) {
		byte[] requestPayload = exchange.getRequestPayload();
		System.out.println( "deviceId:" + getDeviceId(exchange) + ",数据:"+new String(requestPayload));
		exchange.respond(CoAP.ResponseCode.CHANGED,"put status ok");
	}

	@Override
	public void handleGET(CoapExchange exchange) {
		byte[] requestPayload = exchange.getRequestPayload();
		System.out.println( "deviceId:" + getDeviceId(exchange));
		exchange.respond(CoAP.ResponseCode.CONTENT,"get status ok");
	}

	private static String getDeviceId( CoapExchange exchange ){
		return exchange.getRequestOptions().getUriPath().get(1);
	}

}